package com.ruoyi.business.controller;

import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.business.domain.vo.TrainVo;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Train;
import com.ruoyi.business.service.ITrainService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 火车管理Controller
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/base/train")
public class TrainController extends BaseController
{
    @Autowired
    private ITrainService trainService;

    /**
     * 查询火车管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:train:list')")
    @GetMapping("/list")
    public TableDataInfo list(Train train)
    {
        startPage();
        List<Train> list = trainService.selectTrainList(train);
        return getDataTable(list);
    }

//    /**
//     * 导入火车管理列表
//     */
//    @PreAuthorize("@ss.hasPermi('base:train:add')")
//    @Log(title = "车站管理", businessType = BusinessType.IMPORT)
//    @PostMapping("/importExcel")
//    public AjaxResult importExcel(MultipartFile file) throws IOException {
//        ExcelUtil<TrainVo> util = new ExcelUtil<TrainVo>(TrainVo.class);
//        List<TrainVo> list = util.importExcel(file.getInputStream());
//        List<Train> trainList = new ArrayList<>();
//        for (TrainVo trainVo : list) {
//            Train train=new Train();
//            train.setId(IdUtil.getSnowflakeNextId());
//            train.setCode(trainVo.getCode());
//            train.setType(trainVo.getType());
//            train.setStart(trainVo.getStart());
//            train.setStartPinyin(trainVo.getStartPinyin());
//            train.setStartTime(Time.valueOf(trainVo.getStartTime()));
//            train.setEnd(trainVo.getEnd());
//            train.setEndPinyin(trainVo.getEndPinyin());
//            train.setEndTime(Time.valueOf(trainVo.getEndTime()));
//            trainList.add(train);
//        }
//        return toAjax(trainService.insertTrains(trainList));
//    }

    /**
     * 导入火车管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:train:add')")
    @Log(title = "车站管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file) throws IOException {
        ExcelUtil<TrainVo> util = new ExcelUtil<TrainVo>(TrainVo.class);
        List<TrainVo> list = util.importExcel(file.getInputStream());

        // 校验唯一性，分离有效数据和无效数据
        List<Map<String, Object>> errorList = new ArrayList<>();
        List<Train> validTrains = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            TrainVo trainVo = list.get(i);
            boolean isDuplicate = false;

            // 检查必填字段
            if (StringUtils.isEmpty(trainVo.getCode()) ||
                    StringUtils.isEmpty(trainVo.getStart()) ||
                    StringUtils.isEmpty(trainVo.getEnd()) ||
                    StringUtils.isEmpty(trainVo.getStartTime()) ||
                    StringUtils.isEmpty(trainVo.getEndTime()) ||
                    StringUtils.isEmpty(trainVo.getStartPinyin()) ||
                    StringUtils.isEmpty(trainVo.getEndPinyin())) {

                Map<String, Object> error = new HashMap<>();
                error.put("rowNum", i + 2);
                
                // 保存所有字段的值
                error.put("id", trainVo.getId() != null ? trainVo.getId().toString() : "");
                error.put("code", trainVo.getCode() != null ? trainVo.getCode() : "");
                error.put("type", trainVo.getType() != null ? trainVo.getType() : "");
                error.put("start", trainVo.getStart() != null ? trainVo.getStart() : "");
                error.put("startPinyin", trainVo.getStartPinyin() != null ? trainVo.getStartPinyin() : "");
                error.put("startTime", trainVo.getStartTime() != null ? trainVo.getStartTime() : "");
                error.put("end", trainVo.getEnd() != null ? trainVo.getEnd() : "");
                error.put("endPinyin", trainVo.getEndPinyin() != null ? trainVo.getEndPinyin() : "");
                error.put("endTime", trainVo.getEndTime() != null ? trainVo.getEndTime() : "");
                error.put("errorMsg", "所有字段都不能为空");
                
                errorList.add(error);
                continue;
            }

            // 检查车次编号是否已存在
            Train existingTrain = trainService.selectTrainByCode(trainVo.getCode());

            if (existingTrain != null) {
                Map<String, Object> error = new HashMap<>();
                error.put("rowNum", i + 2);
                
                // 保存所有字段的值
                error.put("id", trainVo.getId() != null ? trainVo.getId().toString() : "");
                error.put("code", trainVo.getCode() != null ? trainVo.getCode() : "");
                error.put("type", trainVo.getType() != null ? trainVo.getType() : "");
                error.put("start", trainVo.getStart() != null ? trainVo.getStart() : "");
                error.put("startPinyin", trainVo.getStartPinyin() != null ? trainVo.getStartPinyin() : "");
                error.put("startTime", trainVo.getStartTime() != null ? trainVo.getStartTime() : "");
                error.put("end", trainVo.getEnd() != null ? trainVo.getEnd() : "");
                error.put("endPinyin", trainVo.getEndPinyin() != null ? trainVo.getEndPinyin() : "");
                error.put("endTime", trainVo.getEndTime() != null ? trainVo.getEndTime() : "");
                error.put("errorMsg", "车次编号已存在");
                
                errorList.add(error);
                isDuplicate = true;
            }

            // 如果不是重复数据，添加到有效数据列表
            if (!isDuplicate) {
                try {
                    Train train = new Train();
                    train.setId(trainVo.getId());
                    train.setCode(trainVo.getCode());
                    train.setType(trainVo.getType());
                    train.setStart(trainVo.getStart());
                    train.setStartPinyin(trainVo.getStartPinyin());
                    train.setStartTime(Time.valueOf(trainVo.getStartTime()));
                    train.setEnd(trainVo.getEnd());
                    train.setEndPinyin(trainVo.getEndPinyin());
                    train.setEndTime(Time.valueOf(trainVo.getEndTime()));
                    validTrains.add(train);
                } catch (Exception e) {
                    // 处理时间格式错误
                    Map<String, Object> error = new HashMap<>();
                    error.put("rowNum", i + 2);
                    
                    // 保存所有字段的值
                    error.put("id", trainVo.getId() != null ? trainVo.getId().toString() : "");
                    error.put("code", trainVo.getCode() != null ? trainVo.getCode() : "");
                    error.put("type", trainVo.getType() != null ? trainVo.getType() : "");
                    error.put("start", trainVo.getStart() != null ? trainVo.getStart() : "");
                    error.put("startPinyin", trainVo.getStartPinyin() != null ? trainVo.getStartPinyin() : "");
                    error.put("startTime", trainVo.getStartTime() != null ? trainVo.getStartTime() : "");
                    error.put("end", trainVo.getEnd() != null ? trainVo.getEnd() : "");
                    error.put("endPinyin", trainVo.getEndPinyin() != null ? trainVo.getEndPinyin() : "");
                    error.put("endTime", trainVo.getEndTime() != null ? trainVo.getEndTime() : "");
                    error.put("errorMsg", "时间格式错误，请使用HH:MM:SS格式");
                    
                    errorList.add(error);
                }
            }
        }

        // 插入有效数据
        int successCount = 0;
        if (!validTrains.isEmpty()) {
            successCount = trainService.insertTrains(validTrains);
        }

        // 构建响应
        if (!errorList.isEmpty()) {
            // 有部分数据导入失败
            AjaxResult ajaxResult = AjaxResult.error("部分数据导入成功，部分数据导入失败", errorList);
            ajaxResult.put("successCount", successCount); // 添加成功导入的数量
            return ajaxResult;
        } else {
            // 全部数据导入成功
            return AjaxResult.success("成功导入" + successCount + "条数据");
        }
    }

    /**
     * 下载车站导入模板
     */
    @PreAuthorize("@ss.hasPermi('base:platform:export')")
    @Log(title = "车站管理", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 使用自定义模板下载方法，不包含错误原因列
        trainService.downloadCustomTemplate(response);
    }

    /**
     * 导出火车管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:train:export')")
    @Log(title = "火车管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Train train)
    {
        List<Train> list = trainService.selectTrainList(train);
        ExcelUtil<Train> util = new ExcelUtil<Train>(Train.class);
        util.exportExcel(response, list, "火车管理数据");
    }

    /**
     * 获取火车管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:train:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(trainService.selectTrainById(id));
    }

    /**
     * 新增火车管理
     */
    @PreAuthorize("@ss.hasPermi('base:train:add')")
    @Log(title = "火车管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Train train)
    {
        train.setId(IdUtil.getSnowflakeNextId());
        return toAjax(trainService.insertTrain(train));
    }

    /**
     * 修改火车管理
     */
    @PreAuthorize("@ss.hasPermi('base:train:edit')")
    @Log(title = "火车管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Train train)
    {
        return toAjax(trainService.updateTrain(train));
    }

    /**
     * 删除火车管理
     */
    @PreAuthorize("@ss.hasPermi('base:train:remove')")
    @Log(title = "火车管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(trainService.deleteTrainByIds(ids));
    }

    /**
     * 导出原始火车数据 - 保持与导入模板一致的列结构
     */
    @PreAuthorize("@ss.hasPermi('base:train:export')")
    @Log(title = "火车管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportErrorData")
    public void exportErrorData(HttpServletResponse response, @RequestParam(required = false) String errorData) throws IOException {
        if (StringUtils.hasText(errorData)) {
            try {
                // 解析错误数据JSON
                ObjectMapper mapper = new ObjectMapper();
                List<Map<String, Object>> dataList = mapper.readValue(errorData, 
                    mapper.getTypeFactory().constructCollectionType(List.class, Map.class));
                
                // 转换为TrainVo对象列表
                List<TrainVo> trainVoList = new ArrayList<>();
                for (Map<String, Object> item : dataList) {
                    TrainVo trainVo = new TrainVo();
                    
                    // 设置所有字段的值
                    if (item.containsKey("id")) {
                        trainVo.setId(Long.parseLong(item.get("id").toString()));
                    }
                    if (item.containsKey("code")) {
                        trainVo.setCode(item.get("code").toString());
                    }
                    if (item.containsKey("type")) {
                        trainVo.setType(item.get("type").toString());
                    }
                    if (item.containsKey("start")) {
                        trainVo.setStart(item.get("start").toString());
                    }
                    if (item.containsKey("startPinyin")) {
                        trainVo.setStartPinyin(item.get("startPinyin").toString());
                    }
                    if (item.containsKey("startTime")) {
                        trainVo.setStartTime(item.get("startTime").toString());
                    }
                    if (item.containsKey("end")) {
                        trainVo.setEnd(item.get("end").toString());
                    }
                    if (item.containsKey("endPinyin")) {
                        trainVo.setEndPinyin(item.get("endPinyin").toString());
                    }
                    if (item.containsKey("endTime")) {
                        trainVo.setEndTime(item.get("endTime").toString());
                    }
                    if (item.containsKey("errorMsg")) {
                        trainVo.setErrorMsg(item.get("errorMsg").toString());
                    }
                    
                    trainVoList.add(trainVo);
                }
                
                // 使用ExcelUtil导出
                ExcelUtil<TrainVo> util = new ExcelUtil<>(TrainVo.class);
                util.exportExcel(response, trainVoList, "火车管理错误数据");
            } catch (Exception e) {
                logger.error("处理数据失败", e);
                // 导出失败时返回空数据
                ExcelUtil<TrainVo> util = new ExcelUtil<>(TrainVo.class);
                util.exportExcel(response, new ArrayList<>(), "火车管理错误数据");
            }
        } else {
            // 没有错误数据时导出空表
            ExcelUtil<TrainVo> util = new ExcelUtil<>(TrainVo.class);
            util.exportExcel(response, new ArrayList<>(), "火车管理错误数据");
        }
    }

    /**
     * 清空火车数据
     */
    @PreAuthorize("@ss.hasPermi('base:train:remove')")
    @Log(title = "火车管理", businessType = BusinessType.CLEAN)
    @PostMapping("/clear")
    public AjaxResult clear(@RequestBody Map<String, String> passwordMap) {
        String password = passwordMap.get("password");
        System.out.println("密码：" + password);
        // 验证当前用户密码
        if (!SecurityUtils.matchesPassword(password, SecurityUtils.getLoginUser().getPassword())) {
            return AjaxResult.error("密码验证失败");
        }
        return toAjax(trainService.clearTrain());
    }
}
